/*! @file searchthread.cpp
  * @brief Implements class SearchThread
  * @author AK
  * @date 01.07.2012
  */

#include "searchthread.h"
#include "defines.h"
#include "sqlite3.h"
#include <QDebug>
#include <QString>

/** @brief Definition of SearchThread Class
 * @callgraph
 * @callergraph
 *
 * @param *db sqlite3: database handle
 * @param zSql QString: SQL QueryString
 * @param int mb: Size of db
 * @param int caller: who is calling?
 */
SearchThread::SearchThread(sqlite3 *db,
                           QString zSql,
                           int mb,
                           int caller)
{
    stopped = false;
    tmp = db;
    tmpSql = zSql;
    results = NULL;
    tmpErr = NULL;
    tmpMb = mb;
    tmpCal = caller;
}

/** @brief subclasses run() method of QThread
 * @callgraph
 * @callergraph
 */
void SearchThread::run()
{
    Q_EMIT started();

    int rc = sqlite3_get_table(tmp,
                               tmpSql.toLatin1(),
                               &results,
                               &tmpRow,
                               &tmpCol,
                               &tmpErr);

    qDebug() << "SearchThread\t| in thread! " << this->thread();
    qDebug() << "SearchThread\t| in thread! Rows: " << QString::number(tmpRow);
    qDebug() << "SearchThread\t| in thread! Cols: " << QString::number(tmpCol);

    //    ResultSet res;
    res.rc = rc;
    res.sql = tmpSql;
    res.results = results;
    res.rows = tmpRow;
    res.columns = tmpCol;
    res.size = tmpMb;
    res.caller = tmpCal;

    Q_EMIT finished(res);

    this->stop();
}

/** @brief on thread stopped
 * @callgraph
 * @callergraph
 */
void SearchThread::stop()
{
    //    sqlite3_free_table(results);
    //    sqlite3_free(tmpErr);

    stopped = true;

    qDebug() << "SearchThread\t| Stopped threading.";
}

